CREATE TABLE dbo.Customers (
    Id   INT           NOT NULL IDENTITY,
    Name NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED (Id ASC)
);
 
SET IDENTITY_INSERT [dbo].[Customers] ON
INSERT INTO dbo.Customers (Id, Name) VALUES (1, N'Jose Pavarotti');
INSERT INTO dbo.Customers (Id, Name) VALUES (2, N'Roland Mendel');
INSERT INTO dbo.Customers (Id, Name) VALUES (3, N'Horst Kloss');
INSERT INTO dbo.Customers (Id, Name) VALUES (4, N'Maria Larsson');
INSERT INTO dbo.Customers (Id, Name) VALUES (5, N'Patricia McKenna');
SET IDENTITY_INSERT [dbo].[Customers] OFF
 
CREATE TABLE dbo.Orders
(
    Id INT NOT NULL IDENTITY, 
    CustomerId INT NOT NULL, 
    Amount MONEY NOT NULL, 
    PlacedDate DATETIME NOT NULL, 
    PRIMARY KEY CLUSTERED (Id ASC),
    CONSTRAINT FK_Orders_ToCustomer 
        FOREIGN KEY (CustomerId) REFERENCES Customers(Id)
);
 
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (1, 30, '2012-01-02');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (1, 35, '2012-01-03');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (1, 20, '2012-01-05');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (2, 18, '2012-01-03');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (2, 23, '2012-01-01');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (2, 22, '2012-02-17');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (3, 32, '2012-01-18');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (3, 18, '2012-01-11');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (4, 25, '2012-01-22');
INSERT dbo.Orders (CustomerId, Amount, PlacedDate) VALUES (5, 50, '2012-02-29');


CREATE FUNCTION [dbo].[FrequentCustomers] (@minOrders int)
RETURNS TABLE
AS
RETURN
(
       SELECT Customers.* 
       FROM dbo.Customers
       WHERE @minOrders <= (
                     SELECT COUNT(Orders.Id) 
                     FROM Orders 
                     WHERE Orders.CustomerID = Customers.Id) 
)